package cn.echo.ecc.service.impl;

import cn.echo.ecc.domain.RecommendCode;
import cn.echo.ecc.mapper.RecommendCodeMapper;
import cn.echo.ecc.service.IRecommendCodeService;
import cn.echo.ecc.util.QRCodeGenerator;
import cn.echo.ecc.util.StrUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-10-04
 */
@Service
public class RecommendCodeServiceImpl extends ServiceImpl<RecommendCodeMapper, RecommendCode> implements IRecommendCodeService {

    @Override
    public String getCode() {
        Long userId = 3L;
        RecommendCode recommendCode = getRecommendCodeByUserId(userId);
        if (recommendCode == null) {
            saveRecommendCode(userId);
            recommendCode = getRecommendCodeByUserId(userId);
        }
        return "http://127.0.0.1:6003/reg.phone.html?code=" + recommendCode.getCode();
    }

    private RecommendCode getRecommendCodeByUserId(Long userId) {
        Wrapper<RecommendCode> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",userId);
        return selectOne(wrapper);
    }

    private void saveRecommendCode(Long userId) {
        String code = StrUtils.getComplexRandomString(4);
        RecommendCode recommendCode = new RecommendCode();
        recommendCode.setCode(code);
        recommendCode.setUserId(userId);
        insert(recommendCode);
    }

    public RecommendCode getRecommendCodeByCode(String code) {
        Wrapper<RecommendCode> wrapper = new EntityWrapper<>();
        wrapper.eq("code",code);
        return selectOne(wrapper);
    }

    @Override
    public void deleteByCode(String code) {
        Wrapper<RecommendCode> wrapper = new EntityWrapper<>();
        wrapper.eq("code",code);
        delete(wrapper);
    }

    @Override
    public String getQRCode() {
        String url = getCode();
        String qrCode = QRCodeGenerator.generateQRCodeImage(url);
        return qrCode;
    }

}

